package com.incar.chuxing.utils;

import android.app.Dialog;
import android.content.DialogInterface;

import com.incar.chuxing.utils.Dialogs.PostDialog;

import java.util.ArrayList;
import java.util.Queue;

public class DialogQueue {

    private Queue<Dialog> dialogQueue = new UniqueQueue<>();
    private Dialog currentDialog = null; // 当前显示的对话框
    private Boolean topDialogShow = false;
    private ArrayList<Dialog> allShownDialog = new ArrayList<>();


    public void showDialog(Dialog dialog) {
        //防止一个dialog重复show
        if (dialog != null && dialog.isShowing()) {
            return;
        }


        if (dialog instanceof PostDialog) {//海报弹框是否弹出
            dialog.show();
            allShownDialog.add(dialog);

            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    allShownDialog.remove(dialog);
                    topDialogShow = false;
                    showDialog(null);
                }
            });
            topDialogShow = true;
            return;
        }


        if (topDialogShow) {//海报弹出，则后续的不弹出
            if (dialog != null) {
                dialogQueue.offer(dialog);//添加到队列一个dialog
            }

        } else {//海报未弹出，则后续立即弹出
            if (dialog != null) {
                dialogQueue.offer(dialog);//添加到队列一个dialog
            }

            if (currentDialog == null) {
                currentDialog = dialogQueue.poll();
                if (currentDialog != null) {
                    currentDialog.show();
                    allShownDialog.add(currentDialog);
                    currentDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            allShownDialog.remove(dialog);
                            currentDialog = null;
                            showDialog(null);//消失一个后，弹出下一个dialog
                        }
                    });
                }
            }
        }
    }


    public void dismissAllDialog() {
        dialogQueue.clear();
        for (Dialog dialog : allShownDialog) {
            Logger.i("dismiss", "dismisss");
            dialog.dismiss();
        }
    }



    private static volatile DialogQueue instance = null;

    private DialogQueue(){
    }

    public static DialogQueue getInstance() {
        if (instance == null) {
            synchronized (DialogQueue.class) {
                if (instance == null) {
                    instance = new DialogQueue();
                }
            }
        }
        return instance;
    }

}
